route.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { auth } from "../../auth";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. import { GEMINI_BASE_URL, Google } from "@/app/constant";
  5. async function handle(
  6. req: NextRequest,
  7. { params }: { params: { path: string[] } },
  8. ) {
  9. console.log("[Google Route] params ", params);
  10. if (req.method === "OPTIONS") {
  11. return NextResponse.json({ body: "OK" }, { status: 200 });
  12. }
  13. const controller = new AbortController();
  14. const serverConfig = getServerSideConfig();
  15. let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
  16. if (!baseUrl.startsWith("http")) {
  17. baseUrl = `https://${baseUrl}`;
  18. }
  19. if (baseUrl.endsWith("/")) {
  20. baseUrl = baseUrl.slice(0, -1);
  21. }
  22. let path = `${req.nextUrl.pathname}`.replaceAll("/api/google/", "");
  23. console.log("[Proxy] ", path);
  24. console.log("[Base Url]", baseUrl);
  25. // this fix [Org ID] undefined in server side if not using custom point
  26. if (serverConfig.openaiOrgId !== undefined) {
  27. console.log("[Org ID]", serverConfig.openaiOrgId);
  28. }
  29. const timeoutId = setTimeout(
  30. () => {
  31. controller.abort();
  32. },
  33. 10 * 60 * 1000,
  34. );
  35. const fetchUrl = `${baseUrl}/${path}?key=${req.nextUrl.searchParams.get(
  36. "key",
  37. )}`;
  38. const fetchOptions: RequestInit = {
  39. headers: {
  40. "Content-Type": "application/json",
  41. "Cache-Control": "no-store",
  42. },
  43. method: req.method,
  44. body: req.body,
  45. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  46. redirect: "manual",
  47. // @ts-ignore
  48. duplex: "half",
  49. signal: controller.signal,
  50. };
  51. try {
  52. const res = await fetch(fetchUrl, fetchOptions);
  53. // to prevent browser prompt for credentials
  54. const newHeaders = new Headers(res.headers);
  55. newHeaders.delete("www-authenticate");
  56. // to disable nginx buffering
  57. newHeaders.set("X-Accel-Buffering", "no");
  58. return new Response(res.body, {
  59. status: res.status,
  60. statusText: res.statusText,
  61. headers: newHeaders,
  62. });
  63. } finally {
  64. clearTimeout(timeoutId);
  65. }
  66. }
  67. export const GET = handle;
  68. export const POST = handle;
  69. export const runtime = "edge";
  70. export const preferredRegion = [
  71. "arn1",
  72. "bom1",
  73. "cdg1",
  74. "cle1",
  75. "cpt1",
  76. "dub1",
  77. "fra1",
  78. "gru1",
  79. "hnd1",
  80. "iad1",
  81. "icn1",
  82. "kix1",
  83. "lhr1",
  84. "pdx1",
  85. "sfo1",
  86. "sin1",
  87. "syd1",
  88. ];